package com.xingchi.tornado.storage.core.config;

import com.xingchi.tornado.storage.core.FileStorageService;
import com.xingchi.tornado.storage.core.exception.FileUploadException;
import com.xingchi.tornado.storage.core.supports.LocalFileStorageService;
import com.xingchi.tornado.storage.core.supports.MinioFileStorageService;
import com.xingchi.tornado.storage.core.supports.OSSFileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 文件存储相关配置
 *
 * @author xingchi
 * @date 2024/5/3 19:54
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({StorageProperties.class})
public class FileStorageConfiguration {


    @Bean
    @ConditionalOnProperty(value = StorageProperties.STORAGE_CONFIG_PREFIX, havingValue = "local")
    public FileStorageService localFileStorageService(StorageProperties storageProperties) {
        StorageProperties.LocalProperties local = storageProperties.getLocal();

        if (local == null) {
            throw new FileUploadException("local file storage service init failed, local properties is null");
        }

        log.info("local file storage service init, file path: {}", local.getFilePath());
        return new LocalFileStorageService(storageProperties.getLocal());
    }

    @Bean
    @ConditionalOnProperty(value = StorageProperties.STORAGE_CONFIG_PREFIX, havingValue = "minio")
    public FileStorageService minioFileStorageService(StorageProperties storageProperties) {
        StorageProperties.MinioProperties minio = storageProperties.getMinio();

        if (minio == null) {
            throw new FileUploadException("minio file storage service init failed, minio properties is null");
        }

        log.info("minio file storage service init, endpoint: {}, bucket name: {}", minio.getEndpoint(), minio.getBucketName());
        return new MinioFileStorageService(storageProperties.getMinio());
    }

    @Bean
    @ConditionalOnProperty(value = StorageProperties.STORAGE_CONFIG_PREFIX, havingValue = "aliyun")
    public FileStorageService ossFileStorageService(StorageProperties storageProperties) {
        StorageProperties.OSSProperties oss = storageProperties.getOss();

        if (oss == null) {
            throw new FileUploadException("oss file storage service init failed, oss properties is null");
        }

        log.info("oss file storage service init, endpoint: {}, bucket name: {}", oss.getEndpoint(), oss.getBucketName());
        return new OSSFileStorageService(storageProperties.getOss());
    }

}

